def bilinear_interpolation(image,angle,center,y_min,y_max):
    '''对倾斜字体进行双线性插值'''
    center_x, center_y=center
    h,w=image.shape
    dst=np.zeros((h,w),dtype=np.uint8)

    for r in range(h):
        for c in range(w):
            #计算原图上的坐标
            i = r
            if r<center_y:
                j=c+(center_y-r)/math.tan(angle)
            elif r>center_y:
                j=c-(r-center_y)/math.tan(angle)
            else:
                j=c

            #计算源图上的四个近邻点
            x_0=max(int(np.floor(j)),0)
            y_0=max(int(np.floor(i)),0)
            x_1=min(x_0+1,w-1)
            y_1=min(y_0+1,h-1)

            #双线性插值
            if (x_0 >=x_1) or (y_0>=y_1):
                continue

            value0=((x_1-j)*image[y_0,x_0]+(j-x_0)*image[y_0,x_1])
            value1=((x_1-j)*image[y_1,x_0]+(j-x_0)*image[y_1,x_1])
            dst[r,c]=int(((y_1-i)*value0+(i-y_0)*value1))

    return dst


def correct_slanted_fonts(image,mask,angle):
    '''倾斜字体的矫正'''
    h,w=mask.shape

    # 计算倾斜字体的中心点
    center_x=0
    center_y=0
    num=0
    for r in range(h):
        for c in range(w):
            if mask[r,c]==255:
                center_x+=c
                center_y+=r
                num+=1

    center_x=center_x//num
    center_y=center_y//num

    #计算文本的上下边界
    ver_vec=np.sum(mask,axis=1)
    up=0
    down=0
    h=ver_vec.shape[0]
    for i in range(h):
        if ver_vec[i]!=0:
            up=i
            break
    for i in range(h-1,-1,-1):
        if ver_vec[i]!=0:
            down=i
            break

    #对图像进行双线性插值
    dst=bilinear_interpolation(image,angle,(center_x,center_y),up,down)

    # cv2.namedWindow("test1",0)
    # cv2.imshow("test1", dst)
    # cv2.waitKey(0)
    return dst